# uncompyle6 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)]
# Embedded file name: C:\Users\myh\Desktop\juqi\juqidjango\juqidjango\juqi_server\quanjushang\views.py
# Compiled at: 2023-02-06 17:42:02
# Size of source mod 2**32: 5849 bytes
from django.shortcuts import render
from django.core.handlers.wsgi import WSGIRequest
from django.http import JsonResponse, HttpResponse
from django.core.cache import caches
from rest_framework import status
from django.db import transaction
from django.core.paginator import Paginator
from django.core.cache import cache
from django.views import View
from jqexception.jqexecption import (
    jq_try,
    UnknowErr,
    RaffleBusyErr,
    RightErr,
    NullErr,
    ReqMethodErr,
    ValueErr,
    BalanceInsufficientErr,
)
from typing import Any
from juqiadmin.auth import login_auth, JuqiUser
from .models import (
    QuanjushangGame,
    QuanjushangBindMethod,
    QuanjushangSonGame,
    QuanjushangRecord,
    QuanjushangGood,
)
from .ser import (
    QuanjushangGameSerializer,
    QjsRecordser,
    QuanjushangSonGameSerializer,
    QuanjushangGoodSerializer,
    QuanjushangGamSer,
    QjsGoosinGameser,
    XcxQjsOneInfo,
    Percentage_calculation,
)
from wxuser.models import (
    Users,
    UserHunJingRecord,
    UserScoreRecord,
    UserStoredMoneyRecord,
    UserOrder,
    add_user_order_goods,
)
from rest_framework.parsers import JSONParser
from warehouse.models import JuqiGood
import random
from juqiadmin.models import (
    Finance,
    get_game_finance,
    get_wxuser_finance,
    update_finnce_profit,
)
from jqpage.pagination import JQPagination
from jqgame.basegame import GameType
from .ser import save_UserPackages
from warehouse.serializers import JuqiGoodSerializer
from warehouse.models import GoodLevel
from wxcloudrun.views import order_uuid


# 全局赏游戏商品类型
# post 创建商品类型
# get 获取所有商品类型


# 获取池子下的箱子
class AdminGameson(View):
    """
    箱子
    """

    @jq_try
    @login_auth
    def get(self, request: WSGIRequest, *args: Any, **kwargs: Any):
        u = kwargs["user_info"]
        if u.type != "admin":
            raise RightErr

        limit = int(request.GET.get("limit", 10))
        curPage = int(request.GET.get("page", 1))
        game_uuid = request.GET.get("game_uuid")

        game_ = QuanjushangSonGame.objects.filter(deleted=False).filter(
            game_uuid=game_uuid
        )
        pages = Paginator(game_, limit)
        paged = pages.page(curPage)

        game_data = QuanjushangSonGameSerializer(paged, many=True).data

        res = {
            "code": 0,
            "data": game_data,
            "data_count": pages.count,
            "page_count": pages.num_pages,
        }
        return JsonResponse(res, status=(status.HTTP_200_OK), safe=False)


# 全局赏对局
# get 获取全局赏全部类型
# post 创建全局赏对局
class Game(View):
    """
    管理员用户
    get 全局赏对局list
    post 创建全局赏对局
    put 全局赏对局开启关闭和隐藏
    """

    @login_auth
    def get(self, request: WSGIRequest, *args: Any, **kwargs: Any):
        u = kwargs["user_info"]
        if u.type != "admin":
            raise RightErr

        limit = int(request.GET.get("limit", 10))
        curPage = int(request.GET.get("page", 1))
        state = request.GET.get("state", None)

        _game = QuanjushangGame.objects.filter(deleted=False)
        if state != None:
            _game = _game.filter(state=state)
        pages = Paginator(_game, limit)
        paged = pages.page(curPage)

        game_data = QuanjushangGamSer(paged, many=True).data

        res = {
            "code": 0,
            "data": game_data,
            "data_count": pages.count,
            "page_count": pages.num_pages,
        }
        return JsonResponse(res, status=(status.HTTP_200_OK), safe=False)

    @login_auth
    @transaction.atomic
    def put(self, request: WSGIRequest, *args: Any, **kwargs: Any):
        u = kwargs["user_info"]
        if u.type != "admin":
            raise RightErr

        body: dict = JSONParser().parse(request)

        game_uuid = body.pop("game_uuid")
        radio = body.pop("radio", 1)  # 1上架 下架 2隐藏 不隐藏 3删除

        game_ = QuanjushangGame.objects.filter(uuid=game_uuid).first()
        # 上架下架
        if radio == 1:
            if game_.state == 0:
                game_.state = 1
            else:
                game_.state = 0
        # 隐藏 不隐藏
        if radio == 2:
            if game_.hide_stats == 0:
                game_.hide_stats = 1
            else:
                game_.hide_stats = 0

        # 删除
        if radio == 3:
            game_.deleted = True

        game_.save()

        res = {
            "code": 0,
            "msg": "ok",
        }
        return JsonResponse(res, status=(status.HTTP_200_OK), safe=False)

    @login_auth
    @transaction.atomic
    def post(self, request: WSGIRequest, *args: Any, **kwargs: Any):
        body: dict = JSONParser().parse(request)

        name = body.pop("name")
        # 封面url
        cover_url = body.pop("cover_url")
        # 用户单词抽奖
        user_limit = body.pop("user_limit")

        # 模式uuid
        # method_uuid = body.pop('method_uuid')
        # 价格
        price = body.pop("price")
        # 游戏局数
        game_num = body.pop("game_num", 1)

        # 串串赏开启
        is_ccs = body.pop("ccs", 0)
        # 空车赏开启
        is_kc = body.pop("kc", 0)
        # 返积分
        is_fjf = body.pop("fjf", 0)
        # 返积分数量
        fjf_num = body.pop("fjf_num", 0)
        # 是否只开启积分支付
        jf_pay = body.pop("jf_pay", 0)

        chizi = QuanjushangGame.objects.create(
            name=name,
            cover_url=cover_url,
            user_limit=user_limit,
            price=price,
            game_num=game_num,
            is_ccs=is_ccs,
            is_care=is_kc,
            score_pay=jf_pay,
            is_fjf=is_fjf,
            fjf_num=fjf_num,
        )

        songame_ = []
        for v in range(1, game_num + 1):
            i = {}
            i["game_uuid"] = chizi.uuid
            i["user_limit"] = user_limit
            i["price"] = price
            i["box_num"] = v
            songame_.append(QuanjushangSonGame(**i))

        QuanjushangSonGame.objects.bulk_create(songame_)

        return JsonResponse(
            {"code": 0, "data": QuanjushangGamSer(chizi, many=False).data},
            status=(status.HTTP_201_CREATED),
            safe=False,
        )


# 管理员修改池子全局参数
class AdminUpdateGame(View):
    """
    管理员用户修改池子
    """

    @login_auth
    def get(self, request: WSGIRequest, *args: Any, **kwargs: Any):
        u = kwargs["user_info"]
        if u.type != "admin":
            raise RightErr

        game_uuid = request.GET.get(
            "game_uuid",
        )

        _game = QuanjushangGame.objects.filter(uuid=game_uuid).first()
        if not _game:
            raise NullErr

        game_data = QuanjushangGamSer(_game, many=False).data

        res = {
            "code": 0,
            "data": game_data,
        }
        return JsonResponse(res, status=(status.HTTP_200_OK), safe=False)

    @login_auth
    @transaction.atomic
    def put(self, request: WSGIRequest, *args: Any, **kwargs: Any):
        u = kwargs["user_info"]
        if u.type != "admin":
            raise RightErr

        body: dict = JSONParser().parse(request)
        # 池子uuid
        game_uuid = body.pop("game_uuid")
        game = QuanjushangGame.objects.filter(uuid=game_uuid).first()

        name = body.pop("name")
        cover_url = body.pop("cover_url")
        user_limit = body.pop("user_limit")
        price = body.pop("price")

        game.name = name
        game.cover_url = cover_url
        game.user_limit = user_limit
        game.price = price
        game.save()
        QuanjushangSonGame.objects.filter(game_uuid=game_uuid).update(
            price=price, user_limit=user_limit
        )
        return JsonResponse(
            {"code": 0, "data": QuanjushangGamSer(game, many=False).data},
            status=(status.HTTP_200_OK),
            safe=False,
        )


# 管理员获取全局赏池子下的奖品
# put 修改全局赏池子下赏品
class GameGoods(View):
    @login_auth
    @jq_try
    def get(self, request: WSGIRequest, *args: Any, **kwargs: Any):
        u = kwargs["user_info"]
        if u.type != "admin":
            raise RightErr

        game_uuid = request.GET.get(
            "game_uuid",
        )
        # 取出gameuuid下的赏品
        game = QuanjushangSonGame.objects.filter(game_uuid=game_uuid).first()
        goods_ = (
            QuanjushangGood.objects.filter(son_uuid=game.uuid)
            .filter(deleted=False)
            .all()
        )
        data = QjsGoosinGameser(goods_, many=True).data
        res = {"code": 0, "data": data}
        return JsonResponse(res, status=(status.HTTP_200_OK), safe=False)

    @login_auth
    @transaction.atomic
    def put(self, request: WSGIRequest, *args: Any, **kwargs: Any):
        u = kwargs["user_info"]
        if u.type != "admin":
            raise RightErr

        body: dict = JSONParser().parse(request)
        good_uuid = body.pop("good_uuid")

        name = body.pop("name")
        ip_family = body.pop("ip_famliy", "其他")
        img_url = body.pop("display_url")  # 图片封面
        img_descurl = body.pop("desc_url")  # 图片详细Url
        price = body.pop("price")  # 商品显示价格
        recovery_price = body.pop("recovery_price")  # 商品回收价格

        desc = body.pop("desc")
        _juqi = JuqiGood.objects.filter(uuid=good_uuid).select_for_update().first()
        _juqi.name = name
        _juqi.display_url = img_url
        _juqi.price = price
        _juqi.recovery_price = recovery_price
        _juqi.detail = desc

        # 池子uuid
        game_uuid = body.pop("game_uuid")

        # 查看什么商品类型
        method_uuid = body.pop("method_uuid")

        # 模式加入商品库
        method_ = GoodLevel.objects.filter(uuid=method_uuid).first()
        if not method_:
            raise UnknowErr

        # 0普通商品 1全局赏商品 2空车赏 3串串赏
        method_level = method_.game_type
        _juqi.level_title = method_.title
        goods_updates = []

        game_uuid_list = []
        son_game = QuanjushangSonGame.objects.filter(game_uuid=game_uuid)
        for item in son_game:
            game_uuid_list.append(item.uuid)

        all_goods = (
            QuanjushangGood.objects.filter(good_uuid=good_uuid)
            .filter(son_uuid__in=game_uuid_list)
            .all()
        )
        for i in all_goods:
            i.price = price
            i.good_title = method_.title
            i.good_name = name
            i.good_type = method_level
            i.good_desc = desc
            i.good_url = img_url
            i.good_descurl = img_descurl
            i.recovery_price = recovery_price  # 商品回收价值
            if method_level == 2 or method_level == 3:
                i.num = method_.num  # 触发商品体哦见
            goods_updates.append(i)

        QuanjushangGood.objects.bulk_update(
            goods_updates,
            fields=[
                "price",
                "good_title",
                "good_name",
                "good_type",
                "good_desc",
                "good_url",
                "good_descurl",
                "recovery_price",
                "num",
            ],
            batch_size=1000,
        )
        _juqi.save()
        goods_ = QuanjushangGood.objects.filter(good_uuid=good_uuid).first()
        data = QjsGoosinGameser(goods_, many=False).data
        res = {"code": 0, "data": data}
        return JsonResponse(res, status=(status.HTTP_200_OK), safe=False)

    @login_auth
    @transaction.atomic
    def delete(self, request: WSGIRequest, *args: Any, **kwargs: Any):
        u = kwargs["user_info"]
        if u.type != "admin":
            raise RightErr

        body: dict = JSONParser().parse(request)
        good_uuid = body.pop("good_uuid")
        game_uuid = body.pop("game_uuid")
        game_uuid_list = []
        son_game = QuanjushangSonGame.objects.filter(game_uuid=game_uuid)
        for item in son_game:
            game_uuid_list.append(item.uuid)

        all_goods = (
            QuanjushangGood.objects.filter(good_uuid=good_uuid)
            .filter(son_uuid__in=game_uuid_list)
            .all()
            .update(deleted=True)
        )
        res = {"code": 0, "msg": "删除成功"}
        return JsonResponse(res, status=(status.HTTP_200_OK), safe=False)


# 在全局赏中加入商品
class CreateGood(View):
    """
    新增商品
    """

    @login_auth
    @transaction.atomic
    def post(self, request: WSGIRequest, *args: Any, **kwargs: Any):
        u = kwargs["user_info"]
        if u.type != "admin":
            raise RightErr

        # 获取池子uuid
        body: dict = JSONParser().parse(request)
        name = body.pop("name")
        ip_family = body.pop("ip_famliy", "其他")
        img_url = body.pop("display_url")  # 图片封面
        img_descurl = body.pop("desc_url")  # 图片详细Url
        price = body.pop("price")  # 商品显示价格
        recovery_price = body.pop("recovery_price")  # 商品回收价格

        desc = body.pop("desc")
        # 模式加入商品库
        method_ = GoodLevel.objects.filter(uuid=method_uuid).first()
        if not method_:
            raise UnknowErr

        # 先创建到Goods
        jq_good = JuqiGood.objects.create(
            name=name,
            display_url=img_url,
            price=price,
            recovery_price=recovery_price,
            game_type="全局赏",
            ip_family=ip_family,
            # 商品详细介绍
            detail=desc,
            level_title=method_.title,
        )
        # 获取游戏下的箱子
        game_uuid = body.pop("game_uuid")

        # 查看什么商品类型
        method_uuid = body.pop("method_uuid")

        # 创建商品数量
        count = body.pop("count")
        ##0普通商品 1全局赏商品 2空车赏 3串串赏
        method_level = method_.method_type

        # 创建商品list
        goods_ = []
        if method_level == 2 or method_level == 3:
            # 获取到所有箱子信息 在箱子中添加各个箱子的商品
            son_game = QuanjushangSonGame.objects.filter(game_uuid=game_uuid).all()
            for v in son_game:
                i = {}
                i["son_uuid"] = v.uuid
                i["good_uuid"] = jq_good.uuid
                i["count"] = count
                i["good_title"] = method_.title  # 商品左上角的展师
                i["price"] = price  # 商品价格
                i["recovery_price"] = recovery_price  # 商品回收价值
                i["rf_count"] = count  # 商品数量
                i["good_name"] = name  # 商品名称
                i["good_type"] = method_level  # 商品等级
                i["good_desc"] = desc  # 商品详情
                i["good_url"] = img_url  # 封面url
                i["good_descurl"] = img_descurl  # 详情url
                i["num"] = method_.num  # 触发商品体哦见
                goods_.append(QuanjushangGood(**i))
        else:
            # 获取到所有箱子信息 在箱子中添加各个箱子的商品
            son_game = QuanjushangSonGame.objects.filter(game_uuid=game_uuid).all()
            for v in son_game:
                i = {}
                i["son_uuid"] = v.uuid
                i["good_uuid"] = jq_good.uuid
                i["count"] = count
                i["price"] = price
                i["rf_count"] = count
                i["good_title"] = method_.title
                i["good_name"] = name
                i["good_type"] = method_level
                i["good_desc"] = desc
                i["good_url"] = img_url
                i["good_descurl"] = img_descurl
                i["recovery_price"] = recovery_price  # 商品回收价值
                goods_.append(QuanjushangGood(**i))

        QuanjushangGood.objects.bulk_create(goods_)
        return JsonResponse(
            {"code": 0, "data": JuqiGoodSerializer(jq_good, many=False).data},
            status=(status.HTTP_201_CREATED),
            safe=False,
        )


# 小程序端获取箱子下的商品
class GamesonGoods(View):
    """
    单个箱子下商品
    """

    @jq_try
    @login_auth
    def get(self, request: WSGIRequest, *args: Any, **kwargs: Any):
        u = kwargs["user_info"]
        if u.type != "wxuser":
            raise RightErr

        son_uuid = request.GET.get("sonuuid")
        if not son_uuid:
            raise UnknowErr

        game_ = QuanjushangGood.objects.filter(deleted=False).filter(son_uuid=son_uuid)
        if not game_:
            raise UnknowErr

        game_data = QuanjushangGoodSerializer(game_, many=True).data

        num_list = {}
        index_list = {}
        for _v in game_data:
            if _v["good_type"] == 0:
                num_list[_v["uuid"]] = _v["rf_count"]
                index_list[_v["uuid"]] = game_data.index(_v)

        calcula = Percentage_calculation(num_list)

        for item in calcula:
            _index = index_list[item]
            if calcula[item] == "nan%":
                game_data[_index]["calcula"] = "0%"
            else:
                game_data[_index]["calcula"] = calcula[item]

        res = {"code": 0, "data": game_data}
        return JsonResponse(res, status=(status.HTTP_200_OK), safe=False)


class GameSonInfo(View):
    @jq_try
    @login_auth
    def get(self, request: WSGIRequest, *args: Any, **kwargs: Any):
        u = kwargs["user_info"]
        if u.type != "wxuser":
            raise RightErr

        game_uuid = request.GET.get("son_uuid")

        game_ = (
            QuanjushangSonGame.objects.filter(deleted=False)
            .filter(uuid=game_uuid)
            .first()
        )

        game_data = XcxQjsOneInfo(game_, many=False).data
        res = {
            "code": 0,
            "data": game_data,
        }
        return JsonResponse(res, status=(status.HTTP_200_OK), safe=False)


# 小程序获取一个池子下的全部箱子
class GameSon(View):
    """
    箱子
    """

    @jq_try
    @login_auth
    def get(self, request: WSGIRequest, *args: Any, **kwargs: Any):
        u = kwargs["user_info"]
        if u.type != "wxuser":
            raise RightErr
        limit = int(request.GET.get("limit", 10))
        curPage = int(request.GET.get("page", 1))
        game_uuid = request.GET.get("game_uuid")

        game_ = QuanjushangSonGame.objects.filter(deleted=False).filter(
            game_uuid=game_uuid
        )
        pages = Paginator(game_, limit)
        paged = pages.page(curPage)

        game_data = QuanjushangSonGameSerializer(paged, many=True).data

        res = {
            "code": 0,
            "data": game_data,
            "data_count": pages.count,
            "page_count": pages.num_pages,
        }
        return JsonResponse(res, status=(status.HTTP_200_OK), safe=False)


# 管理员获取中奖记录
class GameRecoder(View):
    @login_auth
    @jq_try
    def get(self, request: WSGIRequest, *args: Any, **kwargs: Any):
        u = kwargs["user_info"]
        if u.type != "admin":
            raise RightErr

        # 箱子uuid
        game_uuid = request.GET.get("game_uuid")

        game = QuanjushangRecord.objects.filter(songame_uuid=game_uuid).all()
        data_list = []
        for item in game:
            _recode = {}
            _recode["seat_number"] = item.seat_number
            _recode["createdAt"] = item.createdAt.strftime(format="%Y-%m-%d %H:%M:%S")
            _good = JuqiGood.objects.filter(uuid=item.good_uuid).first()
            _recode["good_name"] = _good.name
            _recode["good_discplay_url"] = _good.display_url
            _user = Users.objects.filter(uuid=item.user_uuid).first()

            _recode["user_name"] = _user.nickname
            _recode["user_head_url"] = _user.head_url
            data_list.append(_recode)

        res = {"code": 0, "data": data_list}
        return JsonResponse(res, status=(status.HTTP_200_OK), safe=False)


class XcxGameRecoder(View):
    @login_auth
    @jq_try
    def get(self, request: WSGIRequest, *args: Any, **kwargs: Any):
        u = kwargs["user_info"]
        if u.type != "wxuser":
            raise RightErr

        # 箱子uuid
        game_uuid = request.GET.get("son_uuid")

        game = QuanjushangRecord.objects.filter(songame_uuid=game_uuid).all()
        data_list = []
        for item in game:
            _recode = {}
            _recode["seat_number"] = item.seat_number
            _recode["createdAt"] = item.createdAt.strftime(format="%Y-%m-%d %H:%M:%S")
            _good = JuqiGood.objects.filter(uuid=item.good_uuid).first()
            _recode["good_name"] = _good.name
            _recode["good_discplay_url"] = str(_good.display_url)
            _user = Users.objects.filter(uuid=item.user_uuid).first()

            _recode["user_name"] = _user.nickname
            _recode["user_head_url"] = _user.head_url
            data_list.append(_recode)

        res = {"code": 0, "data": data_list}
        return JsonResponse(res, status=(status.HTTP_200_OK), safe=False)


# 小程序获取全部池子
# 小程序抽奖
class RaffleView(View):
    """
    全部对局
    """

    @jq_try
    @login_auth
    def get(self, request: WSGIRequest, *args: Any, **kwargs: Any):
        u = kwargs["user_info"]
        if u.type != "wxuser":
            raise RightErr

        limit = int(request.GET.get("limit", 10))
        curPage = int(request.GET.get("page", 1))

        game_ = QuanjushangGame.objects.filter(state=1, deleted=False)
        pages = Paginator(game_, limit)
        paged = pages.page(curPage)

        game_data = QuanjushangGameSerializer(paged, many=True).data
        res = {"code": 0, "data": game_data, "page_count": pages.num_pages}
        return JsonResponse(res, status=(status.HTTP_200_OK), safe=False)

    @jq_try
    @login_auth
    @transaction.atomic
    def post(self, request: WSGIRequest, *args: Any, **kwargs: Any):
        u = kwargs["user_info"]
        if u.type != "wxuser":
            raise RightErr

        openid = u.openid

        body: dict = JSONParser().parse(request)
        game_uuid = body.pop("son_uuid")  # 箱子Uuid

        stored_money = body.pop("stored_money", 0)
        hunjing = body.pop("hunjing", 0)
        score = body.pop("score", 0)
        raffle_count = body.pop("raffle_count", 1)  # 抽奖次数
        seat_number = body.pop("seat_number", None)  # 座位号

        # 查询用户
        user = (
            Users.objects.filter(openid=openid)
            .filter(deleted=False)
            .select_for_update()
            .first()
        )
        if not user:
            raise NullErr

        # 箱子对局
        game = (
            QuanjushangSonGame.objects.filter(uuid=game_uuid)
            .filter(stats=1)
            .filter(deleted=False)
            .first()
        )
        if not game:
            res = {"code": -1, "msg": "箱子已被抽完"}
            return JsonResponse(res, status=(status.HTTP_200_OK), safe=False)

        if raffle_count > game.user_limit:
            raise UnknowErr

        # 游戏的总池子
        game_stats = (
            QuanjushangGame.objects.filter(uuid=game.game_uuid)
            .filter(state=1)
            .filter(deleted=False)
            .first()
        )
        if not game_stats:
            res = {"code": -1, "msg": "池子已下架"}
            return JsonResponse(res, status=(status.HTTP_200_OK), safe=False)

        if game_stats.score_pay == 1:
            if hunjing == 1 or stored_money == 1:
                return UnknowErr

        # 抽奖次数
        record = (
            QuanjushangRecord.objects.filter(user_uuid=user.uuid)
            .filter(songame_uuid=game.uuid)
            .select_for_update()
            .count()
        )

        if record >= game.user_limit:
            res = {"code": -1, "msg": f"当前抽奖已达到上限,只允许抽取{game_stats.user_limit}次"}
            return JsonResponse(res, status=(status.HTTP_200_OK), safe=False)

        user_order = UserOrder(
            user_uuid=user.uuid,
            game_uuid=game_stats.uuid,
            son_uuid=game.uuid,
            box_num=game.box_num,
            orderid=order_uuid(prefix="CS_"),
            game_name=game_stats.name,
            price=game_stats.price,
            num=raffle_count,
            game_type=GameType.quanjushang.value,
        )

        if stored_money == 1 and hunjing == 1 and score == 1:
            raise UnknowErr

        currency = 0
        if stored_money == 1:
            currency += user.stored_money
        if hunjing == 1:
            currency += user.hunjing
        if score == 1:
            currency += user.score

        sum_price = game.price * raffle_count
        dzf = game.price * raffle_count
        if currency < sum_price:
            res = {"code": -1, "msg": "余额不足"}
            return JsonResponse(res, status=(status.HTTP_200_OK), safe=False)

        if stored_money == 1:
            # 如果余额小于支付金额 扣完余额
            if user.stored_money < sum_price:
                user_order.money = user.stored_money
                _old = user.stored_money
                _new = _old - user.stored_money
                dzf = dzf - user.stored_money
                user.stored_money = _new

            else:
                user_order.money = dzf
                _old = user.stored_money
                _new = _old - dzf
                user.stored_money = _new
                dzf = 0

            zfje = user_order.money

            _record = {
                "user_uuid": user.uuid,
                "stored_money": -zfje,
                "old_stored_money": _old,
                "new_stored_money": _new,
                "detail": f"消耗余额{zfje}:{game_stats.name}抽奖{raffle_count}次",
            }
            UserStoredMoneyRecord.objects.create(**_record)

        if hunjing == 1 and dzf > 0:
            # 如果余额支付存在 并且dzf不等于0
            if stored_money == 1 and dzf != 0:
                # 如果待支付余额大于魂晶 报错
                if dzf > user.hunjing:
                    raise UnknowErr
                # 如果小于魂晶执行
                else:
                    user_order.hunjing = dzf
                    _old = user.hunjing
                    _new = _old - dzf
                    dzf = dzf - user_order.hunjing
                    user.hunjing = _new

            # 条件不满足直接扣除
            else:
                user_order.hunjing = game_stats.price
                _old = user.hunjing
                _new = _old - sum_price
                user.hunjing = _new
                dzf = 0

            zfje = user_order.hunjing
            _record = {
                "user_uuid": user.uuid,
                "hunjing": -zfje,
                "old_hunjing": _old,
                "new_hunjing": _new,
                "detail": f"消耗魂晶{zfje}:{game_stats.name}抽奖{raffle_count} 次",
            }
            UserHunJingRecord(**_record).save()

        if score == 1 and dzf > 0:
            if stored_money == 1 or hunjing == 1:
                raise UnknowErr
            # if (stored_money == 1 and dzf != 0) or (hunjing == 1 and dzf != 0):
            #     if user.score < dzf:
            #         raise UnknowErr

            #     user_order.score = dzf
            #     _old = user.score
            #     _new = _old - dzf
            #     dzf = dzf - user_order.score
            #     user.score = _new

            # else:
            user_order.score = game_stats.price
            _old = user.score
            _new = _old - sum_price
            user.score = _new
            dzf = 0

            zfje = user_order.score
            _record = {
                "user_uuid": user.uuid,
                "score": -zfje,
                "old_score": _old,
                "new_score": _new,
                "detail": f"消耗积分 {zfje}: {game_stats.name} 抽奖 {raffle_count} 次",
            }
            UserScoreRecord(**_record).save()
        if dzf != 0:
            raise UnknowErr

        user_order.save()

        # 背包Info
        packages_info = []

        user_order_goods_uuid = []

        finace_list = []

        quanjushang_finance = get_game_finance(GameType.quanjushang)
        quanjushang_finance.all_raffle_income += sum_price

        user_finace = get_wxuser_finance(
            user_uuid=user.uuid,
            gameType=GameType.quanjushang,
            game_uuid=game_stats.uuid,
        )
        user_finace.all_raffle_income += sum_price

        # 拿出所有普通的商品
        goods = (
            QuanjushangGood.objects.filter(son_uuid=game_uuid)
            .filter(deleted=False)
            .filter(good_type=0)
            .filter(rf_count__gt=0)
            .select_for_update()
        )

        if not goods:
            transaction.set_rollback(True)  # 强制回滚
            res = {"code": -1, "msg": "手慢奖品已经被抽完了~"}
            return JsonResponse(res, status=(status.HTTP_200_OK), safe=False)

        # 商品剩余数量
        rf_allcount = 0
        # 最大座位数
        max_seat_number = 0
        for item in goods:
            # 剩余数量
            rf_allcount += item.rf_count
            # 最大座位号
            max_seat_number += item.count

        # 判断当前座位是否已被坐下
        record_all = QuanjushangRecord.objects.filter(
            songame_uuid=game.uuid
        ).select_for_update()
        if seat_number:
            if record_all.filter(seat_number=seat_number).exists():
                transaction.set_rollback(True)  # 强制回滚
                res = {"code": -1, "msg": "当前座位已被坐下"}
                return JsonResponse(res, status=(status.HTTP_200_OK), safe=False)
        # 随机座位
        else:
            # 座位号列表  已经做下的座位数
            record_num = []
            for v in record_all:
                record_num.append(v.seat_number)
            # 做大座位数
            seat_true = [
                v for v in range(1, max_seat_number + 1) if v not in record_num
            ]
            # 拿到座位
            seat_number = random.choice(seat_true)

        # 随机选择一个可以派奖的赏品
        goods_choice = random.choice(goods)
        # 剩余数量-1
        goods_choice.rf_count -= 1
        user_finace.all_raffle_cost += goods_choice.recovery_price

        # 计算利润
        user_finace.all_raffle_profit = (
            user_finace.all_raffle_income - user_finace.all_raffle_cost
        )

        finace_list.append(user_finace)
        # 管理员添加奖品成本
        quanjushang_finance.all_raffle_cost += goods_choice.recovery_price

        packages_info.append(
            {
                "user_uuid": user.uuid,
                "good_uuid": goods_choice.good_uuid,
                "count": 1,
                "seat_number": seat_number,
                "game_name": game_stats.name,
                "game_uuid": game_stats.uuid,
                "son_uuid": game.uuid,
                "good_name": goods_choice.good_name,
            }
        )
        user_order_goods_uuid.append(goods_choice.good_uuid)

        save_UserPackages(
            packages_info,
            game_type=GameType.quanjushang,
        )

        add_user_order_goods(user_order.uuid, user_order_goods_uuid)  # 添加用户当前抽到的商品到订单里面

        # 用于串串赏派奖
        record_info = {}
        record_info_number = {}
        rf_allcount -= 1
        # 如果普通奖品全部派完,派出全局赏
        if rf_allcount == 0:
            packages_good_info = []

            # 派奖励全局赏奖品
            qjs_goods = (
                QuanjushangGood.objects.filter(son_uuid=game_uuid)
                .filter(deleted=False)
                .filter(good_type=1)
                .filter(rf_count__gt=0)
                .select_for_update()
            )

            # 在所有中奖记录中拿出所有用户Uuid开始派奖,这个池子中的全部普通商品中奖记录
            zhong_record = QuanjushangRecord.objects.filter(songame_uuid=game.uuid)
            # 全局赏的奖品派发逻辑 循环所有全局赏奖品派发
            for v in qjs_goods:
                # 循环全局赏奖品数量
                for _ in range(v.count):
                    zhong_user = random.choice(zhong_record)
                    zhong_user_order = (
                        UserOrder.objects.filter(deleted=False)
                        .filter(game_type=GameType.quanjushang.value)
                        .filter(user_uuid=zhong_user.user_uuid)
                        .filter(game_uuid=zhong_user.game_uuid)
                        .filter(son_uuid=zhong_user.songame_uuid)
                        .filter(box_num=game.box_num)
                        .first()
                    )
                    if game_stats.is_care == 1:
                        ca_key = str(game_stats.uuid) + str(zhong_user.user_uuid)
                        cache.set(ca_key, "0")

                        # cach_user = cache.get(ca_key)
                        # if cach_user != None:
                        #     cache.delete(ca_key)

                    # 修改finace 加入成本价格
                    fina_ = False
                    for x in finace_list:
                        # 说明查到过
                        if zhong_user.user_uuid == x.user_uuid:
                            x.all_raffle_cost += v.recovery_price
                            fina_ = True
                            break

                    if fina_ == False:
                        user_finace = get_wxuser_finance(
                            user_uuid=zhong_user.user_uuid,
                            gameType=GameType.quanjushang,
                            game_uuid=zhong_user.game_uuid,
                        )
                        user_finace.all_raffle_cost += v.recovery_price
                        user_finace.all_raffle_profit = (
                            user_finace.all_raffle_income - user_finace.all_raffle_cost
                        )

                        # user_finace = update_finnce_profit(user_finace)  # 计算一下盈亏
                        finace_list.append(user_finace)

                    # 判断是否已存在背包内
                    if not packages_good_info:
                        packages_good_info.append(
                            {
                                "user_uuid": zhong_user.user_uuid,
                                "good_uuid": v.good_uuid,
                                "count": 1,
                                "seat_number": zhong_user.seat_number,
                                "game_name": game_stats.name,
                                "game_uuid": game_stats.uuid,
                                "son_uuid": game.uuid,
                                "good_name": v.good_name,
                            }
                        )
                        record_info[zhong_user.user_uuid] = 1
                        record_info_number[
                            zhong_user.user_uuid
                        ] = zhong_user.seat_number
                    else:
                        pack_ = False
                        for j in packages_good_info:
                            if (
                                j["user_uuid"] == zhong_user.user_uuid
                                and j["good_uuid"] == v.good_uuid
                            ):
                                j["count"] += 1

                                record_info[zhong_user.user_uuid] += 1
                                pack_ = True
                                break
                        if pack_ == False:
                            packages_good_info.append(
                                {
                                    "user_uuid": zhong_user.user_uuid,
                                    "good_uuid": v.good_uuid,
                                    "count": 1,
                                    "seat_number": zhong_user.seat_number,
                                    "game_name": game_stats.name,
                                    "game_uuid": game_stats.uuid,
                                    "son_uuid": game.uuid,
                                    "good_name": v.good_name,
                                }
                            )

                            if record_info.get(zhong_user.user_uuid):
                                record_info[zhong_user.user_uuid] += 1
                            else:
                                record_info[zhong_user.user_uuid] = 1

                            record_info_number[
                                zhong_user.user_uuid
                            ] = zhong_user.seat_number

                    add_user_order_goods(
                        zhong_user_order.uuid, [v.good_uuid]
                    )  # 添加用户当前抽到的商品到订单里面
                    v.rf_count -= 1

                v.save()
                # 加入成本价格
                quanjushang_finance.all_raffle_cost += v.recovery_price * v.count
            # 空车赏玩法
            if game_stats.is_care == 1:
                all_user = []
                zhongjiang_user = []

                # 拿出中奖名单和 全局赏中奖名单比对 把没中间的用户放到一个列表中
                for v_ in zhong_record:
                    all_user.append(v_.user_uuid)

                for s_ in record_info:
                    zhongjiang_user.append(s_)

                data = set(all_user).difference(set(zhongjiang_user))
                miss_user = list(data)
                # 对比俩个列表拿出差集 未中奖用户

                care_goods = (
                    QuanjushangGood.objects.filter(son_uuid=game_uuid)
                    .filter(deleted=False)
                    .filter(good_type=2)
                    .first()
                )

                for m_ in miss_user:
                    cache_key = str(game_stats.uuid) + str(m_)
                    miss_num = cache.get(cache_key)
                    # 如果第一次
                    if miss_num == None:
                        cache.set(cache_key, "1")
                    else:
                        if int(miss_num) + 1 >= care_goods.num:
                            # 派奖逻辑
                            care = (
                                QuanjushangGood.objects.filter(
                                    good_uuid=care_goods.good_uuid
                                )
                                .filter(deleted=False)
                                .filter(rf_count__gt=0)
                                .first()
                            )

                            # 修改finace 加入成本价格
                            fina_ = False
                            for x in finace_list:
                                # 说明查到过
                                if m_ == x.user_uuid:
                                    x.all_raffle_cost += care.recovery_price
                                    fina_ = True
                                    break

                            if fina_ == False:
                                user_finace = get_wxuser_finance(
                                    user_uuid=m_,
                                    gameType=GameType.quanjushang,
                                    game_uuid=game_stats.uuid,
                                )
                                user_finace.all_raffle_cost += care.recovery_price
                                user_finace.all_raffle_profit = (
                                    user_finace.all_raffle_income
                                    - user_finace.all_raffle_cost
                                )

                                finace_list.append(user_finace)
                            _seat = (
                                QuanjushangRecord.objects.filter(user_uuid=m_)
                                .filter(son_uuid=game.uuid)
                                .first()
                            )
                            packages_good_info.append(
                                {
                                    "user_uuid": m_,
                                    "good_uuid": care.good_uuid,
                                    "count": 1,
                                    "seat_number": _seat.seat_number,
                                    "game_name": game_stats.name,
                                    "game_uuid": game_stats.uuid,
                                    "son_uuid": game.uuid,
                                    "good_name": care.good_name,
                                }
                            )

                            care.rf_count -= 1
                            care.save()
                            # 加入成本价格
                            quanjushang_finance.all_raffle_cost += care.recovery_price

                            cache.set(cache_key, "0")
                        else:
                            cache.set(cache_key, str(int(miss_num) + 1))
            # 串串赏玩法
            if game_stats.is_ccs == 1:
                ccs_goods = (
                    QuanjushangGood.objects.filter(son_uuid=game_uuid)
                    .filter(deleted=False)
                    .filter(good_type=3)
                    .filter(rf_count__gt=0)
                    .order_by("-num")
                    .select_for_update()
                )

                ccs_users = []

                # 循环箱子串串赏奖品
                for v in ccs_goods:
                    # 循环串串赏奖品要派出的数量
                    for _ in range(v.count):
                        for key, values in record_info.items():
                            # 如果这个用户中全局赏次数大于等于 设定值
                            if values >= v.num:
                                if key in ccs_users:
                                    continue
                                # 循环背包记录信息
                                _pack = False
                                for j in packages_good_info:
                                    # 如果已经中了这个串串赏不给他了
                                    if (
                                        j["user_uuid"] == key
                                        and j["good_uuid"] == v.good_uuid
                                    ):
                                        _pack = True
                                        break

                                if _pack == False:
                                    packages_good_info.append(
                                        {
                                            "user_uuid": key,
                                            "good_uuid": v.good_uuid,
                                            "count": 1,
                                            "seat_number": record_info_number.get(key),
                                            "game_name": game_stats.name,
                                            "game_uuid": game_stats.uuid,
                                            "son_uuid": game.uuid,
                                            "good_name": v.good_name,
                                        }
                                    )

                                    # 修改finace 加入成本价格

                                _fina = False
                                for x in finace_list:
                                    if key == x.user_uuid:
                                        x.all_raffle_cost += v.recovery_price
                                        _fina = True
                                        break

                                if _fina == False:
                                    user_finace = get_wxuser_finance(
                                        user_uuid=zhong_user.user_uuid,
                                        gameType=GameType.quanjushang,
                                        game_uuid=game_stats.uuid,
                                    )
                                    user_finace.all_raffle_cost += v.recovery_price
                                    user_finace.all_raffle_profit = (
                                        user_finace.all_raffle_income
                                        - user_finace.all_raffle_cost
                                    )
                                    finace_list.append(user_finace)

                                ccs_users.append(key)
                                quanjushang_finance.all_raffle_cost += v.recovery_price
                                # record_info.pop(key)
                                v.rf_count -= 1
                                v.save()
            # 返积分玩法
            if game_stats.is_fjf == 1:
                all_user = []
                zhongjiang_user = []

                # 拿出中奖名单和 全局赏中奖名单比对 把没中间的用户放到一个列表中
                for v_ in zhong_record:
                    all_user.append(v_.user_uuid)

                for s_ in record_info:
                    zhongjiang_user.append(s_)

                data = set(all_user).difference(set(zhongjiang_user))
                miss_user = list(data)
                for item in miss_user:
                    # 用户uuid
                    _u = Users.objects.filter(uuid=item).select_for_update().first()
                    _old = _u.score
                    _new = _u.score + game_stats.fjf_num
                    _u.score = _new
                    _u.save()
                    # 创建记录
                    _record = {
                        "user_uuid": user.uuid,
                        "score": game_stats.fjf_num,
                        "old_score": _old,
                        "new_score": _new,
                        "detail": f"{game_stats.name} 返还积分  {game_stats.fjf_num} ",
                    }
                    UserScoreRecord(**_record).save()

            save_UserPackages(
                packages_good_info,
                game_type=GameType.quanjushang,
            )

            # 锁定箱子
            game.stats = 0
            game.save()

        # 减去金额
        user.save()
        # 商品数量-1 save
        goods_choice.save()

        quanjushang_finance = update_finnce_profit(quanjushang_finance)  # 计算一下盈亏
        # 管理员更新 finance
        quanjushang_finance.save()

        Finance.objects.bulk_update(
            finace_list, ["all_raffle_income", "all_raffle_cost", "all_raffle_profit"]
        )

        data = QuanjushangGoodSerializer(goods_choice, many=False).data

        res = {"code": 0, "good": data}
        return JsonResponse(res, status=(status.HTTP_200_OK), safe=False)


# 空车赏获取num
class CareNum(View):
    @jq_try
    @login_auth
    def get(self, request: WSGIRequest, *args: Any, **kwargs: Any):
        u = kwargs["user_info"]
        if u.type != "wxuser":
            raise RightErr

        game_uuid = request.GET.get("game_uuid")

        openid = u.openid

        user = Users.objects.filter(openid=openid).filter(deleted=False).first()
        if not user:
            raise NullErr

        care_num = 0

        cache_key = str(game_uuid) + str(user.uuid)

        cach_user = cache.get(cache_key)
        if cach_user:
            care_num = cach_user

        res = {"code": 0, "num": care_num}
        return JsonResponse(res, status=(status.HTTP_200_OK), safe=False)


# okay decompiling views.cpython-37.pyc
